var {appUtils, logUtils, gUtils} = require ('../../utils/index');
function App (appName, config) {
  this.appName = appName;
  this.count = 0;
  this.maxCount = config.maxCount || null;
  this.interval = config.interval || null;
  this.autoClose = config.autoClose;
  this.isOverToday = false;
}
App.prototype.run = function () {};
App.prototype.checkInstall = function () {
  var installed = appUtils.checkInstall (this.appName);
  if (!installed) {
    logUtils.log (this.appName, '未安装');
    return false;
  }
  return true;
};
App.prototype.checkInterval = function () {
  if (this.interval && this.lastEndTime) {
    var hasExec = gUtils.hasExec (this.lastEndTime);
    if (hasExec < this.interval) {
      logUtils.log (this.appName, '时间未到，跳过', this.interval, '|', hasExec);
      return false;
    }
  }
  return true;
};
App.prototype.checkCount = function () {
  if (this.maxCount && this.count > this.maxCount) {
    logUtils.log (this.appName, '超过次数，跳过', this.maxCount, '|', this.count);
    return false;
  }
  return true;
};
App.prototype.check = function () {
  if (!this.checkInstall ()) {
    return;
  }
  if (!this.checkInterval ()) {
    return;
  }
  if (!this.checkCount ()) {
    return;
  }
  if (this.isOverToday) {
    return;
  }
  return true;
};
App.prototype.exec = function () {};
App.prototype.main = function () {
  if (!this.check ()) {
    return;
  }
  logUtils.log (this.appName, 'run', this.count);
  appUtils.openApp (this.appName);
  gUtils.sleep (6, 10);
  this.run (this.count);
  this.count++;
  this.lastEndTime = Date.now ();
  if (this.autoClose) {
    gUtils.sleep (2, 4);
    appUtils.closeRecent ();
  }
};
module.exports = App;
